"""
FastAPI应用主入口
"""
import asyncio
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse

from app.config import get_settings
from app.core.redis_client import get_redis_client
from app.core.kafka_client import get_kafka_client
from app.core.background_tasks import start_background_tasks, stop_background_tasks
from app.utils.logger import setup_logger
from app.api import kafka, topics, messages, websocket, producer, monitor, topic_manager, ksql, data_generator
from app.api import settings as settings_api

# 获取配置
settings = get_settings()

# 设置日志
logger = setup_logger()


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    logger.info(f"启动 {settings.app.name} v{settings.app.version}")

    # 打印配置信息用于调试
    logger.info(f"Redis配置: {settings.redis.host}:{settings.redis.port}")
    logger.info(f"Kafka配置: {settings.kafka.bootstrap_servers}")

    # 启动时初始化
    try:
        # 初始化Redis连接
        redis_client = await get_redis_client()
        await redis_client.ping()
        logger.info("Redis连接成功")
        
        # 初始化Kafka客户端
        kafka_client = get_kafka_client()
        logger.info("Kafka客户端初始化成功")

        # 自动加载并应用保存的Kafka配置
        try:
            from app.core.redis_client import redis_manager
            saved_config = await redis_manager.get_json("kafka:config:connection")
            if saved_config:
                logger.info("发现保存的Kafka配置，尝试自动连接...")
                # 测试保存的配置是否有效
                result = await kafka_client.test_connection_with_fallback()
                if result["success"]:
                    logger.info(f"Kafka自动连接成功: {result['message']}")
                else:
                    logger.warning(f"Kafka自动连接失败: {result['message']}")
            else:
                logger.info("未发现保存的Kafka配置，等待手动配置")
        except Exception as e:
            logger.warning(f"Kafka自动连接过程中出错: {e}")

        # 启动后台任务
        try:
            await start_background_tasks()
            logger.info("后台任务启动成功")
        except Exception as e:
            logger.warning(f"后台任务启动失败: {e}")

        logger.info("应用启动完成")
        
    except Exception as e:
        logger.error(f"应用启动失败: {e}")
        raise
    
    yield
    
    # 关闭时清理
    try:
        # 停止后台任务
        try:
            await stop_background_tasks()
            logger.info("后台任务已停止")
        except Exception as e:
            logger.warning(f"停止后台任务失败: {e}")

        # 关闭Redis连接
        redis_client = await get_redis_client()
        await redis_client.close()
        logger.info("Redis连接已关闭")

        logger.info("应用关闭完成")
        
    except Exception as e:
        logger.error(f"应用关闭时出错: {e}")


# 创建FastAPI应用
app = FastAPI(
    title=settings.app.name,
    version=settings.app.version,
    description="高性能实时Kafka数据观测平台",
    debug=settings.app.debug,
    lifespan=lifespan
)

# 添加CORS中间件
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.api.cors_origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


# 健康检查端点
@app.get("/health")
async def health_check():
    """健康检查"""
    try:
        # 检查Redis连接
        redis_client = await get_redis_client()
        await redis_client.ping()
        redis_status = "healthy"
    except Exception as e:
        redis_status = f"unhealthy: {str(e)}"
    
    return JSONResponse({
        "status": "healthy",
        "app": settings.app.name,
        "version": settings.app.version,
        "redis": redis_status,
    })


# 根路径
@app.get("/")
async def root():
    """根路径"""
    return {
        "message": f"欢迎使用 {settings.app.name}",
        "version": settings.app.version,
        "docs": "/docs",
        "health": "/health"
    }


# 注册API路由
app.include_router(kafka.router, prefix="/api/kafka", tags=["kafka"])
app.include_router(topics.router, prefix="/api/topics", tags=["topics"])
app.include_router(messages.router, prefix="/api/messages", tags=["messages"])
app.include_router(producer.router, tags=["producer"])
app.include_router(monitor.router, prefix="/api/monitor", tags=["monitor"])
app.include_router(topic_manager.router, tags=["topic-manager"])
app.include_router(settings_api.router, prefix="/api/settings", tags=["settings"])
app.include_router(ksql.router, prefix="/api/ksql", tags=["ksql"])
app.include_router(data_generator.router, tags=["data-generator"])
app.include_router(websocket.router, prefix="/ws", tags=["websocket"])


# 全局异常处理
@app.exception_handler(Exception)
async def global_exception_handler(request, exc):
    """全局异常处理"""
    logger.error(f"未处理的异常: {exc}", exc_info=True)
    return JSONResponse(
        status_code=500,
        content={
            "error": "内部服务器错误",
            "message": str(exc) if settings.app.debug else "服务暂时不可用"
        }
    )


if __name__ == "__main__":
    import uvicorn
    
    uvicorn.run(
        "app.main:app",
        host=settings.api.host,
        port=settings.api.port,
        reload=settings.api.reload,
        log_level=settings.app.log_level.lower()
    )
